package com.liuyang.controller;


import cn.hutool.core.lang.Snowflake;
import com.liuyang.common.Result;
import com.liuyang.entity.Disasterimg;
import com.liuyang.entity.Materialsimg;
import com.liuyang.service.DisasterimgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者:caleb
 * @since 2022-02-26
 */
@RestController
@RequestMapping("/system/disasterimg")
public class DisasterimgController {

    @Autowired
    private DisasterimgService disasterimgService;

    @PostMapping("/fileUpload")
    public Result fileUpload(@RequestParam("file") MultipartFile[] files) {
        List<String> imgIds = new ArrayList<>();
        try {
            for(MultipartFile f : files) {
                File dir = new File("D:\\upload");
                if(!dir.exists()) {
                    dir.mkdirs();
                }

                Snowflake snowflake = new Snowflake(2,3);
                String id = snowflake.nextIdStr();
                String fileName = f.getOriginalFilename();

                Disasterimg disasterimg = new Disasterimg();
                disasterimg.setId(id);
                fileName = id + fileName.substring(fileName.indexOf("."));
                disasterimg.setImgName(fileName);
                disasterimg.setImgPath("D:\\upload\\" + fileName);
                imgIds.add(id); // id 列表
                disasterimgService.saveOrUpdate(disasterimg);

                f.transferTo(new File("D:\\upload\\" + fileName));
            }
        } catch (IOException e) {
            return Result.succ("图片上传失败");
        }

        return Result.succ(200, "图片上传成功", imgIds);
    }
}
